//
//  ViewController.m
//  baodongPro
//
//  Created by feng on 15/11/17.
//  Copyright © 2015年 proper. All rights reserved.
//
#define adjustNumber  4
#define rightControlBtnWH  50.f
#define spaceTime    3
#define  ScreenW   [UIScreen mainScreen].bounds.size.width
#define  ScreenH   [UIScreen mainScreen].bounds.size.height
#import "MainViewController.h"
#import "Masonry.h"
#import "UIView+FBDQuickCreateUI.h"
#import "People.h"
#import "AppDelegate.h"
#import "UMSocial.h"
#import "FBDLoginViewController.h"

@interface MainViewController ()<NSURLSessionDelegate,UMSocialUIDelegate,UMSocialDataDelegate>
{
    NSURL* _myURL;
    NSURLRequest *_myRequest;
    NSURLSession* _mySession;
    UIImageView* _testImageView;
    NSArray* urlsArray;
    People* yingXuan;
    UIButton* rightControlButton;
    NSTimer*_musicTimer;
    BOOL isPlaying;
    
}
@end

@implementation MainViewController
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    isPlaying=NO;
    urlsArray=@[
                @"http://b383.photo.store.qq.com/psb?/fdd93bbb-0860-4d99-8a9a-17ec67b4a15d/JIbrH0MQnygXjwXRI0lGGvhgQt6XhvrC8oNbH2NtVMk!/b/dH8BAAAAAAAA&bo=IAMrBAAAAAAFAC8!&rf=viewer_311.jpg",
                @"http://b382.photo.store.qq.com/psb?/fdd93bbb-0860-4d99-8a9a-17ec67b4a15d/1TLu3hqdN1lk5KkStKXzXSTzwz8p.4Z7amhTdWrBaVs!/b/dH4BAAAAAAAA&bo=gAJVAwAAAAAFAPc!&rf=viewer_311.jpg",
                @"http://a2.qpic.cn/psb?/V11ShKH41icPra/A7Ql6TcdJwN7vFZMsHhudWxAScsw8jQq7FlF6eqDCZw!/b/dKYAAAAAAAAA&bo=gAJuBAAAAAAFAMs!&rf=viewer_4.jpg",
                @"http://a2.qpic.cn/psb?/V11ShKH41icPra/2eRUtqVHA51zJQ2ookaD*DIbq51AFYvAE40tnTXQBe8!/b/dKYAAAAAAAAA&bo=gAJuBAAAAAAFAMs!&rf=viewer_4.jpg",
                @"http://b251.photo.store.qq.com/psb?/V11ShKH41icPra/XPqGqW8DYEdjAOwdRz*K5tuVlT7UcMYk8vWSKGzA3VU!/b/dPsAAAAAAAAA&bo=gAJVAwAAAAAFAPc!&rf=viewer_4.jpg",
                @"http://b162.photo.store.qq.com/psb?/V11ShKH41icPra/06gwG.pl4Ukm.W552Q.PC4GZio4uZe4TmDkrgxqjmCc!/b/dKIAAAAAAAAA&bo=gAJVAwAAAAAFAPc!&rf=viewer_4.jpg"];
    
    [self testDemoWithDrution:arc4random()%3+2];
    [self testDmeo2];
    [self testDmeo2];
    
    
    rightControlButton=[[UIButton alloc ] initWithFrame:CGRectMake(ScreenW-80, 86, rightControlBtnWH, rightControlBtnWH)];
    [rightControlButton setTitle:@"乐" forState:UIControlStateNormal];
    rightControlButton.backgroundColor=[UIColor purpleColor];
    rightControlButton.userInteractionEnabled=YES;
    self.view.userInteractionEnabled=YES;
    [rightControlButton addTarget:self action:@selector(rightControlButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    rightControlButton.layer.cornerRadius=rightControlBtnWH/2.0;
    [self.view addSubview:rightControlButton];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    urlsArray=nil;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor blackColor];
    
   AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    FBDMenuViewController* tageMenuVC=nil;
    if ([appDelegate fbd_menuVC])
    {
        tageMenuVC=[appDelegate fbd_menuVC];
    }
    
    
    // 显示 FBDMenu的按钮
    UIBarButtonItem* menuItemButton=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:tageMenuVC action:@selector(menuItemBarPressed:)];
    self.navigationItem.leftBarButtonItem=menuItemButton;
    // 左划右划的手势
    UISwipeGestureRecognizer* mySwipGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:tageMenuVC action:@selector(mySwipGestureDidSwiped:)];
   mySwipGesture.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:mySwipGesture];
    
    
    mySwipGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:tageMenuVC action:@selector(mySwipGestureDidSwiped:)];
    mySwipGesture.direction=UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:mySwipGesture];
    // 显示 分享的按钮
    UIBarButtonItem* shareItemButton=[[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareItemBarPressed:)];
    // 显示 分享的按钮
    UIBarButtonItem* thridLoginItemButton=[[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(thridLoginItemButtonBarPressed:)];
    self.navigationItem.rightBarButtonItems=@[shareItemButton,thridLoginItemButton];;
    
    
    
    
    
    
    
    
    
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
-(void)menuItemBarPressed:(id)sender
{

}
-(void)mySwipGestureDidSwiped:(UISwipeGestureRecognizer*)sender
{


}
/**
 *      @author 冯宝东
 *
 *      友盟分享
 *
 *      @param sender sender
 */

-(void)shareItemBarPressed:(id)sender
{
    UIImage* agoImage=[UIImage imageNamed:@"IMG_0299.JPG"];
    NSData* currentImageData=UIImageJPEGRepresentation(agoImage, 0.1);
    UIImage *currentImage=[UIImage imageWithData:currentImageData];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56e23ecee0f55af03b000a7e"
                                      shareText:@"迎萱宝宝 儿童App的社会分享功能已经完成！欢迎查看代码,git clone APP code,https://git.oschina.net/donggehaoya/MyDaughter "
                                     shareImage:currentImage
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToQQ,UMShareToWechatSession,UMShareToSms,UMShareToSina,UMShareToWechatTimeline,nil]
                                       delegate:self];
    

  [UMSocialData defaultData].extConfig.qqData.url = @"http://baidu.com";
    

}
/**
 *      @author 冯宝东
 *
 *      友盟第三方登录
 *
 *      @param sender sender
 */
-(void)thridLoginItemButtonBarPressed:(id)sender
{

    FBDLoginViewController*loginVC=[[FBDLoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:^{
        
        NSLog(@" present login ViewController");
        
    }];

//    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
//    
//    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//        
//        //          获取微博用户名、uid、token等
//        
//        if (response.responseCode == UMSResponseCodeSuccess) {
//            
//            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToTencent];
//            
//            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
//            
//        }});
//    
    
    

}

#pragma mark -------- 音乐控制
-(void)rightControlButtonPressed:(UIButton*)sender
{

    NSLog(@" rightControlButtonPressed ");
    if (!isPlaying)
    {
        
        NSLog(@" rightControlButtonPressed NSTimer");
        isPlaying=YES;
        _musicTimer= [NSTimer scheduledTimerWithTimeInterval:spaceTime/3.0
                                                      target:self
                                                    selector:@selector(timeForRightControlMusic) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_musicTimer forMode:NSRunLoopCommonModes];
        [self    modeForPlayMusic];
        
    }else{
        isPlaying=NO;
        [_musicTimer  invalidate];
        _musicTimer=nil;
        
        [self modeForStopMusic];
    }
    
    

}

-(void)timeForRightControlMusic
{
    
    
    NSLog(@"timeForRightControlMusic runing。。。。。");
    rightControlButton.transform=CGAffineTransformRotate(rightControlButton.transform, -M_PI_4);





}






#pragma mark ------- 闪光模式
-(void)modeForHighLigting
{


    if (!yingXuan)
    {
        yingXuan=[[People alloc] init];
    }
    
    __weak typeof(MainViewController*)weakSelf=self;
    [yingXuan kongzhiWithTime:0.001 ScreenColor:^(UIColor *color) {
        
        weakSelf.view.backgroundColor=color;
        
    }];
    



}


-(void)modeForPlayMusic
{
    if (!yingXuan)
    {
        yingXuan=[[People alloc] init];
        [yingXuan playSoundForMyBabay];
        
    }else
    {
        [yingXuan playSoundForMyBabay];
    }



}

-(void)modeForStopMusic
{


    if (!yingXuan)
    {
        yingXuan=[[People alloc] init];
        [yingXuan stopPlaySoundForMyBabay];
        
    }else
    {
        [yingXuan stopPlaySoundForMyBabay];
    }
    




}



#define spaceW  20
#pragma mark ------Mansony 学习
-(void)studyMansony
{
    for (int i=0; i<20; i++)
    {
        
        UIView*subOneView=[[UIView alloc] init];
        [People kongzhiWithTime:0.5 ScreenColor:^(UIColor *color) {
            subOneView.backgroundColor=color;
            
        }];
        [self.view addSubview:subOneView];
        
        [subOneView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo
            
            make.centerY.mas_equalTo(self.view.mas_centerY);
            make.top.equalTo(self.view.mas_top).with.offset(spaceW*i);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-spaceW*i);
            make.left.equalTo(self.view.mas_left).with.offset(spaceW*i);
            make.right.equalTo(self.view.mas_right).with.offset(-spaceW*i);
            
        }];
    }

}
    
-(void)testDmeo2
{
    [self testDemoWithDrution:arc4random()%3+2];
}

-(void)testDemoWithDrution:(int)durtion
{
    
    //初始化一个ImageView  图片视图
    UIImageView*  testImageView=[[UIImageView alloc] initWithFrame:CGRectMake(arc4random()%(int)ScreenW, arc4random()%(int)ScreenH, 0, 0)];
    testImageView.backgroundColor=[UIColor purpleColor];
    testImageView.alpha=0;
    [self.view addSubview:testImageView];
    

    if (!urlsArray)
    {
        return;
    }
    
    // 配置 一个URL 和 Request 以及苹果推荐的URLSession API
    _myURL=[NSURL URLWithString:[urlsArray objectAtIndex:arc4random()%urlsArray.count] relativeToURL:nil];
    _myRequest=[[NSURLRequest alloc] initWithURL:_myURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
    _mySession=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue: [NSOperationQueue mainQueue]];
    NSURLSessionDataTask*_myTask=[_mySession dataTaskWithRequest:_myRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        UIImage* reciveImage=[UIImage imageWithData:data scale:1.0];
        testImageView.image=reciveImage;
        
        CGFloat imageFrameW=reciveImage.size.width;
        CGFloat imageFrameH=reciveImage.size.height;
        
        int originX = (arc4random()%(int)ScreenW)-imageFrameW/adjustNumber;
        
        originX=originX<0?20+(arc4random()%40):originX;
        
        int originY = (arc4random() % (int)ScreenH)-imageFrameH/adjustNumber ;
        originY=originY<0?100+(arc4random()%80):originY;
        
        [UIView animateWithDuration:durtion animations:^{
            CGRect  BrandomCGRect=CGRectMake( originX, originY, imageFrameW/adjustNumber, imageFrameH/adjustNumber);
            testImageView.frame=BrandomCGRect;
            testImageView.alpha=1;
        } completion:^(BOOL finished) {
            
            [testImageView removeFromSuperview];

            [self testDemoWithDrution:arc4random()%3+1];
            
        }];
        
        
    }];
    
    
    
    [_myTask resume];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
